"""
高级Photoshop解决方案：
1. 保留原始PSD的所有图层
2. 正确添加JSON图片到独立图层
3. 生成可执行的Photoshop脚本
"""

import os
import uuid
import json
import requests
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from pathlib import Path
from datetime import datetime
from config import Config
from enhanced_ps_script_generator import generate_enhanced_photoshop_script

try:
    from psd_tools import PSDImage
    PSD_TOOLS_AVAILABLE = True
except ImportError:
    PSD_TOOLS_AVAILABLE = False

class AdvancedPhotoshopSolution:
    """
    高级Photoshop解决方案
    """
    
    def __init__(self):
        self.export_folder = Config.EXPORT_FOLDER
        self.upload_folder = Config.UPLOAD_FOLDER
    
    def create_advanced_export(self, template, regions, customization_data, export_format='tif', custom_filename=''):
        """
        创建高级导出方案
        """
        print("=== 高级Photoshop解决方案 ===")
        
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_id = str(uuid.uuid4())[:8]
        
        # 1. 处理原始PSD文件
        original_psd_path = None
        canvas_width = template['width']
        canvas_height = template['height']
        
        if template.get('image_path'):
            image_path = template['image_path']
            template_image_path = Path(image_path) if Path(image_path).is_absolute() else self.upload_folder / image_path
            
            if template_image_path.exists() and template_image_path.suffix.lower() == '.psd':
                original_psd_path = template_image_path
                
                if PSD_TOOLS_AVAILABLE:
                    try:
                        psd = PSDImage.open(template_image_path)
                        canvas_width, canvas_height = psd.width, psd.height
                        print(f"原始PSD: {canvas_width}x{canvas_height}, 图层数: {len(list(psd))}")
                    except Exception as e:
                        print(f"读取PSD信息失败: {e}")
        
        # 2. 下载并保存JSON图片到本地
        json_images_info = []
        
        for region_index, region_data in customization_data.get('regions', {}).items():
            elements = region_data.get('elements', [])
            
            for element_idx, element in enumerate(elements):
                image_info = self._download_and_save_json_image(
                    element, region_index, element_idx, timestamp, unique_id
                )
                if image_info:
                    json_images_info.append(image_info)
        
        # 3. 生成增强的Photoshop脚本
        script_path = generate_enhanced_photoshop_script(
            original_psd_path, json_images_info, canvas_width, canvas_height,
            timestamp, unique_id, self.export_folder
        )
        
        # 4. 生成预览合成图像
        preview_path = self._generate_preview_image(
            template, json_images_info, canvas_width, canvas_height,
            timestamp, unique_id, export_format, custom_filename
        )
        
        # 5. 保存使用说明
        instructions_path = self._generate_instructions(
            original_psd_path, script_path, preview_path, json_images_info,
            timestamp, unique_id
        )
        
        print(f"\\n=== 高级方案导出完成 ===")
        print(f"预览图像: {preview_path}")
        print(f"PS脚本: {script_path}")
        print(f"使用说明: {instructions_path}")
        print(f"JSON图片数: {len(json_images_info)}")
        
        return preview_path
    
    def _download_and_save_json_image(self, element, region_index, element_idx, timestamp, unique_id):
        """下载或加载本地JSON图片"""
        image_url = element.get('image_url')
        if not image_url:
            return None
        
        try:
            # 检查是否为本地文件路径
            if image_url.startswith('/uploads/') or image_url.startswith('uploads/'):
                # 处理本地文件
                from pathlib import Path
                from config import Config
                
                # 清理路径
                clean_path = image_url.lstrip('/')
                local_file_path = Path(Config.BASE_DIR) / clean_path
                
                print(f"路径转换调试:")
                print(f"  原始 URL: {image_url}")
                print(f"  清理后路径: {clean_path}")
                print(f"  Config.BASE_DIR: {Config.BASE_DIR}")
                print(f"  完整本地路径: {local_file_path}")
                print(f"  文件是否存在: {local_file_path.exists()}")
                
                if local_file_path.exists():
                    element_image = Image.open(local_file_path)
                    print(f"✅ 成功加载本地文件: {local_file_path}")
                    print(f"  文件大小: {local_file_path.stat().st_size} bytes")
                else:
                    # 列出 uploads 目录内容进行调试
                    uploads_dir = Path(Config.BASE_DIR) / 'uploads'
                    if uploads_dir.exists():
                        files = list(uploads_dir.glob('*'))
                        print(f"  uploads目录中的文件: {[f.name for f in files]}")
                    raise FileNotFoundError(f"本地文件不存在: {local_file_path}")
            else:
                # 处理URL下载
                print(f"下载网络图片: {image_url}")
                response = requests.get(image_url, timeout=30)
                response.raise_for_status()
                element_image = Image.open(BytesIO(response.content))
            
            # 保存到本地
            image_filename = f"json_image_{region_index}_{element_idx}_{timestamp}_{unique_id}.png"
            image_path = self.export_folder / image_filename
            
            # 转换为RGBA并保存
            if element_image.mode != 'RGBA':
                element_image = element_image.convert('RGBA')
            
            element_image.save(image_path, 'PNG')
            
            print(f"保存JSON图片: {image_filename}")
            
            return {
                'original_url': image_url,
                'local_path': str(image_path),
                'filename': image_filename,
                'size': element_image.size,
                'user_data': element.get('user_placement_data', {}),
                'download_success': True
            }
            
        except Exception as e:
            print(f"下载JSON图片失败: {e}")
            
            # 创建占位符图片
            placeholder_filename = f"placeholder_{region_index}_{element_idx}_{timestamp}_{unique_id}.png"
            placeholder_path = self.export_folder / placeholder_filename
            
            placeholder = Image.new('RGBA', (200, 200), (255, 0, 0, 255))
            draw = ImageDraw.Draw(placeholder)
            draw.rectangle([0, 0, 199, 199], outline=(0, 0, 0, 255), width=3)
            draw.text((30, 90), "下载失败", fill=(255, 255, 255, 255))
            placeholder.save(placeholder_path, 'PNG')
            
            return {
                'original_url': image_url,
                'local_path': str(placeholder_path),
                'filename': placeholder_filename,
                'size': (200, 200),
                'user_data': element.get('user_placement_data', {}),
                'download_success': False
            }
    
    def _generate_complete_photoshop_script(self, original_psd_path, json_images_info, canvas_width, canvas_height, timestamp, unique_id):
        """生成完整可执行的Photoshop脚本"""
        script_filename = f"complete_rebuild_{timestamp}_{unique_id}.jsx"
        script_path = self.export_folder / script_filename
        
        script_content = f'''// 完整Photoshop图层重建脚本
// 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
// 
// 使用说明：
// 1. 确保原始PSD文件可访问
// 2. 确保JSON图片文件已下载到exports目录
// 3. 在Photoshop中运行此脚本

// 关闭所有打开的文档
while (app.documents.length > 0) {{
    app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}}

try {{
    // 1. 打开原始PSD文件（保留所有原始图层）
    var originalPsdFile = new File("{original_psd_path.as_posix() if original_psd_path else ''}");
    if (originalPsdFile.exists) {{
        var doc = app.open(originalPsdFile);
        app.activeDocument = doc;
        
        alert("✅ 成功打开原始PSD文件，包含所有原始图层！");
        
        // 2. 添加JSON配置的图片作为新图层
'''
        
        for i, image_info in enumerate(json_images_info):
            user_data = image_info['user_data']
            position = user_data.get('position', {})
            dimension = user_data.get('dimension', {})
            rotation = user_data.get('angle_of_rotation', 0)
            
            script_content += f'''
        // 添加JSON图片 {i+1}
        try {{
            var jsonImageFile = new File("{image_info['local_path'].replace(chr(92), '/')}");
            if (jsonImageFile.exists) {{
                // 打开JSON图片
                var jsonDoc = app.open(jsonImageFile);
                
                // 全选并复制
                jsonDoc.selection.selectAll();
                jsonDoc.selection.copy();
                jsonDoc.close(SaveOptions.DONOTSAVECHANGES);
                
                // 切换到主文档
                app.activeDocument = doc;
                
                // 粘贴为新图层
                var newLayer = doc.paste();
                newLayer.name = "JSON图片_{i+1}";
                
                // 设置图层位置（使用精确的像素单位）
                var targetX = {position.get('x', 0)};
                var targetY = {position.get('y', 0)};
                
                // 获取当前图层的左上角位置
                var currentX = newLayer.bounds[0].as('px');
                var currentY = newLayer.bounds[1].as('px');
                
                // 计算需要移动的距离
                var deltaX = targetX - currentX;
                var deltaY = targetY - currentY;
                
                // 移动图层到目标位置
                newLayer.translate(UnitValue(deltaX, 'px'), UnitValue(deltaY, 'px'));
                
                // 验证位置
                var finalX = newLayer.bounds[0].as('px');
                var finalY = newLayer.bounds[1].as('px');
                
                // 调试信息
                // alert("位置调试:\n" +
                //       "目标位置: (" + targetX + ", " + targetY + ")\n" +
                //       "原始位置: (" + currentX + ", " + currentY + ")\n" +
                //       "移动距离: (" + deltaX + ", " + deltaY + ")\n" +
                //       "最终位置: (" + finalX + ", " + finalY + ")");
                
                // 设置图层尺寸（如果指定）
                {f'''
                var targetWidth = {dimension.get('width', 'null')};
                var targetHeight = {dimension.get('height', 'null')};
                if (targetWidth && targetHeight) {{
                    var currentWidth = newLayer.bounds[2].as('px') - newLayer.bounds[0].as('px');
                    var currentHeight = newLayer.bounds[3].as('px') - newLayer.bounds[1].as('px');
                    var scaleX = targetWidth / currentWidth * 100;
                    var scaleY = targetHeight / currentHeight * 100;
                    newLayer.resize(scaleX, scaleY);
                }}
                ''' if dimension.get('width') and dimension.get('height') else '// 保持原始尺寸'}
                
                // 设置旋转（如果指定）
                {f'newLayer.rotate({rotation});' if rotation != 0 else '// 无旋转'}
                
                alert("✅ 成功添加JSON图片_{i+1}到位置({position.get('x', 0)}, {position.get('y', 0)})");
                
            }} else {{
                alert("❌ JSON图片文件不存在: {image_info['filename']}");
            }}
        }} catch(e) {{
            alert("处理JSON图片_{i+1}时出错: " + e.message);
        }}
'''
        
        script_content += f'''
        // 3. 完成
        alert("🎉 图层重建完成！\\n\\n" +
              "原始图层: 已保留所有{len(json_images_info) if original_psd_path else 0}个原始图层\\n" +
              "新增图层: {len(json_images_info)}个JSON图片图层\\n\\n" +
              "现在您可以看到完整的图层结构！");
              
    }} else {{
        alert("❌ 原始PSD文件不存在，请检查路径：\\n{original_psd_path.as_posix() if original_psd_path else 'No PSD file'}");
    }}
    
}} catch(e) {{
    alert("脚本执行出错: " + e.message);
}}
'''
        
        with open(script_path, 'w', encoding='utf-8') as f:
            f.write(script_content)
        
        return script_path
    
    def _generate_preview_image(self, template, json_images_info, canvas_width, canvas_height, timestamp, unique_id, export_format, custom_filename=''):
        """生成预览图像（仅用于参考）"""
        # 加载原始图像
        composite_image = None
        
        if template.get('image_path'):
            image_path = template['image_path']
            template_image_path = Path(image_path) if Path(image_path).is_absolute() else self.upload_folder / image_path
            
            if template_image_path.exists():
                if template_image_path.suffix.lower() == '.psd':
                    try:
                        from psd_tools import PSDImage
                        psd = PSDImage.open(template_image_path)
                        composite_image = psd.composite()
                    except:
                        pass
                else:
                    try:
                        composite_image = Image.open(template_image_path)
                    except:
                        pass
        
        if not composite_image:
            composite_image = Image.new('RGBA', (canvas_width, canvas_height), (255, 255, 255, 255))
        
        if composite_image.mode != 'RGBA':
            composite_image = composite_image.convert('RGBA')
        
        # 添加JSON图片（仅用于预览）
        for image_info in json_images_info:
            try:
                json_image = Image.open(image_info['local_path'])
                if json_image.mode != 'RGBA':
                    json_image = json_image.convert('RGBA')
                
                # 应用用户设置
                user_data = image_info['user_data']
                dimension = user_data.get('dimension', {})
                if dimension.get('width') and dimension.get('height'):
                    new_size = (int(dimension['width']), int(dimension['height']))
                    json_image = json_image.resize(new_size, Image.Resampling.LANCZOS)
                
                angle = user_data.get('angle_of_rotation', 0)
                if angle != 0:
                    json_image = json_image.rotate(angle, expand=True, fillcolor=(0, 0, 0, 0))
                
                # 使用用户精确位置
                position = user_data.get('position', {})
                x = int(position.get('x', 0))
                y = int(position.get('y', 0))
                
                # 合成（用于预览）
                composite_image.paste(json_image, (x, y), json_image)
                print(f"预览中添加JSON图片: 位置({x}, {y}), 尺寸{json_image.size}")
                
            except Exception as e:
                print(f"预览处理失败: {e}")
        
        # 保存预览图像
        if custom_filename:
            # 清理文件名，移除不安全字符
            import re
            safe_filename = re.sub(r'[<>:"/\\|?*]', '_', custom_filename)
            preview_filename = f"{safe_filename[:50]}.tif"
        else:
            preview_filename = f"preview_{timestamp}_{unique_id}.tif"
        
        preview_path = self.export_folder / preview_filename
        composite_image.save(preview_path, 'TIFF', compression='lzw')
        
        return preview_path
    
    def _generate_instructions(self, original_psd_path, script_path, preview_path, json_images_info, timestamp, unique_id):
        """生成详细的使用说明"""
        instructions_filename = f"instructions_{timestamp}_{unique_id}.txt"
        instructions_path = self.export_folder / instructions_filename
        
        instructions = f'''高级Photoshop图层重建说明
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

📁 生成的文件：
1. 预览图像: {preview_path.name}
2. PS脚本: {script_path.name}
3. 本说明: {instructions_filename}
'''
        
        for i, img_info in enumerate(json_images_info):
            instructions += f"4. JSON图片{i+1}: {img_info['filename']}\n"
        
        instructions += f'''

🎯 完整操作步骤：

步骤1：准备工作
1. 确保Photoshop已安装并运行
2. 确保原始PSD文件可访问: {original_psd_path.name if original_psd_path else 'N/A'}
3. 确保所有JSON图片已下载到exports目录

步骤2：执行脚本
1. 在Photoshop中，选择 文件 > 脚本 > 浏览
2. 选择脚本文件: {script_path.name}
3. 点击"加载"运行脚本

步骤3：验证结果
1. 脚本会自动打开原始PSD文件（保留所有原始图层）
2. 自动添加JSON配置的图片作为新图层
3. 每个JSON图片都会放置在您配置的精确位置

📋 JSON图片详情：
'''
        
        for i, img_info in enumerate(json_images_info):
            user_data = img_info['user_data']
            position = user_data.get('position', {})
            dimension = user_data.get('dimension', {})
            rotation = user_data.get('angle_of_rotation', 0)
            
            instructions += f'''
JSON图片 {i+1}:
  - 文件: {img_info['filename']}
  - 原始URL: {img_info['original_url']}
  - 位置: ({position.get('x', 0)}, {position.get('y', 0)})
  - 尺寸: {dimension.get('width', '原始')} x {dimension.get('height', '原始')}
  - 旋转: {rotation}度
  - 下载状态: {"成功" if img_info['download_success'] else "失败（使用占位符）"}
'''
        
        instructions += f'''

⚠️  重要提醒：
1. 脚本执行后，您将看到完整的图层结构
2. 原始PSD的所有图层都会保留
3. JSON图片会作为独立图层添加
4. 每个图层都可以独立编辑

🎉 这是目前技术条件下的最佳解决方案！
'''
        
        with open(instructions_path, 'w', encoding='utf-8') as f:
            f.write(instructions)
        
        return instructions_path
